<template>
  <div class="payment-detail">
    <div      
      class="payment-mode"
      :class="{ 'self-pay': paymentMode === 'self' }"
    >
      <!-- 支付模式显示部分保持不变 -->
      <!-- <el-icon class="mode-icon">
        <component :is="paymentMode === 'insurance' ? User : Money" />
      </el-icon> -->
      <span  class="mode-text">
        {{ paymentMode === "insurance" ? "职工医保支付" : "自费支付" }}
      </span>
    </div>

    <div class="card">
      <div class="card-header">
        <el-icon class="card-header-icon"><Document /></el-icon>
        <span>费用明细</span>
      </div>

      <!-- 添加未查询到待缴费项目的显示 -->
      <div v-if="!hasPendingPayments" class="no-payments-section">
        <div class="no-payments-content">
          <el-icon class="no-payments-icon"><InfoFilled /></el-icon>
          <div class="no-payments-text">未查询到待缴费项目</div>
          <div class="no-payments-desc">当前就诊号下没有需要支付的费用</div>
        </div>
      </div>

      <!-- 检查费用明细 -->
      <div v-else>
        <div v-if="examinationItems.length > 0" class="fee-section">
          <div class="section-title">检查费用</div>
          <div class="fee-table-wrapper">
            <table class="fee-table">
              <thead>
                <tr>
                  <th class="fee-name">检查项目</th>
                  <th class="fee-amount">项目价格</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(item, index) in examinationItems"
                  :key="'exam-' + index"
                >
                  <td class="fee-name">{{ item.exam_name }}</td>
                  <td class="fee-amount">¥{{ item.unit_price.toFixed(2) }}</td>
                </tr>
              </tbody>
              <tfoot v-if="examinationItems.length > 1">
                <tr class="fee-total-row">
                  <td class="fee-name">检查费用合计</td>
                  <td class="fee-amount">¥{{ examinationTotal.toFixed(2) }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        <!-- 治疗/药品费用明细 -->
        <div v-if="treatmentItems.length > 0" class="fee-section">
          <div class="section-title">治疗费用</div>
          <div class="fee-table-wrapper">
            <table class="fee-table">
              <thead>
                <tr>
                  <th class="fee-name">药品名称</th>
                  <th class="fee-quantity">数量</th>
                  <th class="fee-price">单价</th>
                  <th class="fee-amount">合计</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(item, index) in treatmentItems"
                  :key="'treat-' + index"
                >
                  <td class="fee-name">{{ item.name }}</td>
                  <td class="fee-quantity">
                    {{ item.quantity }}{{ item.unit }}
                  </td>
                  <td class="fee-price">¥{{ item.unitPrice.toFixed(2) }}</td>
                  <td class="fee-amount">¥{{ item.amount.toFixed(2) }}</td>
                </tr>
              </tbody>
              <tfoot v-if="treatmentItems.length > 1">
                <tr class="fee-total-row">
                  <td colspan="3" class="fee-name">药品费用合计</td>
                  <td class="fee-amount">¥{{ treatmentTotal.toFixed(2) }}</td>
                </tr>
              </tfoot>
            </table>
          </div>
        </div>

        <!-- 医保结算信息 -->
        <template v-if="paymentMode === 'insurance'">
          <div class="insurance-section">
            <div class="section-title">医保结算</div>
            <div class="insurance-table">
              <table class="fee-table">
                <tr
                  v-for="(row, index) in insuranceSettlementRows"
                  :key="index"
                >
                  <td class="insurance-name">{{ row.name }}</td>
                  <td class="insurance-value">{{ row.value }}</td>
                </tr>
              </table>
            </div>
          </div>
        </template>

        <!-- 应付金额和提示 -->
        <div class="total-section">
          <div class="payable-amount">
            <span>应付金额：</span>
            <span class="amount">¥{{ payableAmount.toFixed(2) }}</span>
          </div>

          <div v-if="showSelfPaymentTip" class="alert-box">
            <el-icon class="alert-icon"><Warning /></el-icon>
            <span
              >您的医保账户余额不足，需自费支付 ¥{{
                selfPaymentAmount.toFixed(2)
              }}</span
            >
          </div>
        </div>
      </div>
    </div>

    <div class="security-tips">
      <el-icon class="security-icon"><Lock /></el-icon>
      <span>支付安全保证，您的信息不会泄露</span>
    </div>

    <div class="action-buttons">
      <button class="back-button" @click="backHome">返回上一步</button>
      <button
        v-if="hasPendingPayments"
        class="confirm-button"
        @click="confirmPayment"
        :class="{ loading: confirming }"
      >
        {{ confirming ? "进入支付..." : "确认支付" }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElIcon } from "element-plus";
// 引入后端API接口
import { getExamOrderItemListByVisit } from "@/api/selfPaymentService";
import { useRouter } from "vue-router";

const router = useRouter();

const emit = defineEmits(["next-step", "prev-step"]);
// 获取当前患者挂号信息
const currentPatientVisit = JSON.parse(
  localStorage.getItem("currentPatientVisit")
);

// 支付模式：insurance(医保) 或 self(自费)
const paymentMode = ref("insurance");
const confirming = ref(false);

// 检查费用项目
const examinationItems = ref([]);

// 治疗/药品费用项目
const treatmentItems = ref([]);

// 医保相关数据
const insuranceRatio = ref(0.55); // 55%报销比例

// 添加计算属性：判断是否有待缴费项目
const hasPendingPayments = computed(() => {
  return examinationItems.value.length > 0 || treatmentItems.value.length > 0;
});

// 计算属性
const examinationTotal = computed(() => {
  return examinationItems.value.reduce((sum, item) => sum + item.amount, 0);
});

const treatmentTotal = computed(() => {
  return treatmentItems.value.reduce((sum, item) => sum + item.amount, 0);
});

const totalAmount = computed(() => {
  return examinationTotal.value + treatmentTotal.value;
});

// 获取检查订单ID（从第一个检查项目中获取）
const examinationOrderId = computed(() => {
  return examinationItems.value.length > 0
    ? examinationItems.value[0].order_id
    : null;
});

// 获取支付ID（从第一个检查项目中获取）
const paymentId = computed(() => {
  return examinationItems.value.length > 0
    ? examinationItems.value[0].payment_id
    : null;
});

// 医保可报销金额
const reimbursableAmount = computed(() => {
  return totalAmount.value * insuranceRatio.value;
});

// 医保实际支付金额
const insurancePayment = computed(() => {
  return reimbursableAmount.value;
});

// 自费支付金额 - 修复计算逻辑
const selfPaymentAmount = computed(() => {
  if (paymentMode.value === "self") {
    return totalAmount.value;
  } else {
    // 医保支付时，自费部分 = 总金额 - 医保报销金额
    return totalAmount.value - reimbursableAmount.value;
  }
});

// 应付金额（自费部分）- 确保金额正确
const payableAmount = computed(() => {
  // 直接返回自费支付金额，确保没有浮点数精度问题
  const amount = selfPaymentAmount.value;
  return Math.round(amount * 100) / 100; // 四舍五入到2位小数
});

// 是否显示自费支付提示
const showSelfPaymentTip = computed(() => {
  return (
    paymentMode.value === "insurance" &&
    insurancePayment.value < reimbursableAmount.value
  );
});

// 医保结算行数据
const insuranceSettlementRows = computed(() => {
  return [
    {
      name: "医保报销比例",
      value: `${(insuranceRatio.value * 100).toFixed(0)}%`,
    },
    {
      name: "医保可报销金额",
      value: `¥${reimbursableAmount.value.toFixed(2)}`,
    },
    { name: "医保实际支付", value: `¥${insurancePayment.value.toFixed(2)}` },
  ];
});

// 确认支付
const confirmPayment = () => {
  confirming.value = true;

  setTimeout(() => {
    confirming.value = false;
    emit("next-step", {
      amount: payableAmount.value,
      visitNumber: currentPatientVisit.appointment_id,
      examinationItems: examinationItems, //包含了订单信息
      patientName: currentPatientVisit.patient_name,
      // 新增传递的订单和支付信息
      paymentId: paymentId.value,
      examinationOrderId: examinationOrderId.value, // 为了明确用途
      // 传递就诊ID
      visitId: currentPatientVisit.visit_id,
    });
  }, 1000);
};

// 加载费用详细中的检查费用及治疗费用
const loadPendingPaymentDetails = async () => {
  await Promise.all([loadExaminationFees(), loadTreatmentFees()]);
};

// 加载检查项目费用
const loadExaminationFees = async () => {
  //未查询到信息返回空
  if (!currentPatientVisit?.visit_id) {
    examinationItems.value = [];
    return;
  }
  // 专门加载检查项目费用
  try {
    //请求后端
    const response = await getExamOrderItemListByVisit({
      visit_id: currentPatientVisit.visit_id,
    });
    if (response && response.code == 200) {
      console.log(response.data);
      examinationItems.value = response.data;
    }
  } catch (e) {
    console.log(e);
  }
};
// 加载治疗费用
const loadTreatmentFees = async () => {
  // 专门加载治疗项目费用
  // 目前返回空数组，将来实现时再填充数据
  treatmentItems.value = [];
};

//返回上一步：返回首页
const backHome = () => {
  // 清除当前的患者就诊信息
  localStorage.removeItem("currentPatientVisit");
  // 返回扫码页面
  router.push("/self-service");
};

// 初始化加载
onMounted(async () => {
  loadPendingPaymentDetails();
});
</script>

<style lang="scss" scoped>
.payment-detail {
  width: 100%;
}

.payment-mode {
  display: flex;
  align-items: center;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
}

.payment-mode.self-pay {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.mode-icon {
  margin-right: 10px;
  font-size: 20px;
}

.mode-text {
  font-size: 16px;
  font-weight: 500;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 20px;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: #f9fafb;
  border-bottom: 1px solid #eaeef2;
  font-weight: 500;
  color: #1f2f3d;
}

.card-header-icon {
  margin-right: 8px;
  color: #3b82f6;
}

.fee-section {
  padding: 16px;
  border-bottom: 1px solid #eaeef2;

  &:last-of-type {
    border-bottom: none;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.fee-table-wrapper {
  overflow-x: auto;
}

.fee-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.fee-table thead {
  background-color: #f8fafc;
}

.fee-table th {
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  color: #64748b;
  border-bottom: 1px solid #e2e8f0;
}

.fee-table tr {
  border-bottom: 1px solid #f1f5f9;
}

.fee-table tr:last-child {
  border-bottom: none;
}

.fee-table td {
  padding: 12px 16px;
  vertical-align: middle;
}

.fee-name {
  color: #374151;
  text-align: left;
}

.fee-quantity,
.fee-price {
  text-align: center;
  color: #6b7280;
}

.fee-amount {
  text-align: right;
  font-weight: 500;
  color: #1f2f3d;
}

.fee-total-row {
  background-color: #f8fafc;
  font-weight: 600;

  td {
    border-top: 1px solid #e2e8f0;
    padding-top: 14px;
  }
}

.insurance-section {
  padding: 16px;
  border-top: 1px dashed #eaeef2;
}

.insurance-table {
  margin-top: 8px;
}

.insurance-name {
  color: #606266;
  padding: 10px 16px;
}

.insurance-value {
  text-align: right;
  color: #3b82f6;
  font-weight: 500;
  padding: 10px 16px;
}

.total-section {
  padding: 16px;
  background: #f9fafb;
  border-top: 1px solid #eaeef2;
  text-align: right;
}

.payable-amount {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
}

.amount {
  color: #ef4444;
  font-size: 20px;
  font-weight: 600;
  margin-left: 8px;
}

.alert-box {
  padding: 12px 16px;
  background: #fffbeb;
  border: 1px solid #fcd34d;
  border-radius: 4px;
  color: #92400e;
  display: flex;
  align-items: center;
  justify-content: center;
}

.alert-icon {
  margin-right: 8px;
  color: #f59e0b;
}

.security-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 8px;
  color: #0369a1;
  margin: 24px 0;
}

.security-icon {
  margin-right: 8px;
  color: #0ea5e9;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 24px;
}

.back-button {
  flex: 1;
  height: 48px;
  background: white;
  color: #606266;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #f5f7fa;
    border-color: #c0c4cc;
  }
}

.confirm-button {
  flex: 1;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }

  &.loading {
    opacity: 0.7;
    pointer-events: none;
  }
}

// 未查询到待缴费项目的样式
.no-payments-section {
  padding: 60px 20px;
  text-align: center;
}

.no-payments-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.no-payments-icon {
  font-size: 64px;
  color: #cbd5e1;
}

.no-payments-text {
  font-size: 18px;
  font-weight: 600;
  color: #64748b;
}

.no-payments-desc {
  font-size: 14px;
  color: #94a3b8;
}

@media (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
  }

  .fee-table td,
  .fee-table th {
    padding: 10px 12px;
  }

  .section-title {
    font-size: 15px;
  }

  .fee-table {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .fee-table {
    min-width: 400px; // 确保在小屏幕上表格可以水平滚动
  }

  .fee-section {
    padding: 12px;
  }
}
</style>